package com.frxuexi.park2304.news

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.NewsBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.RequestType
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.DateTimeUtils
import com.frxuexi.park2304.R
import com.frxuexi.park2304.databinding.ActivityNesAddBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/app/NesAddActivity")
@AndroidEntryPoint
class NesAddActivity : BaseActivity<ActivityNesAddBinding,NewsIntent,NewsViewModel>() {
    override val binding: ActivityNesAddBinding by lazy { ActivityNesAddBinding.inflate(layoutInflater)}
    override val vm: NewsViewModel by viewModels<NewsViewModel>()
    val newsImgAdapter by lazy { NewsImgAdapter() }
    val imgs = mutableListOf<String>()

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.UPLOAD->{
                                val date = it.data as String
                                val name = date.split(":")[1]
                                imgs.add( "http://10.161.9.80:2209/images/news/${
                                    SPUtils.getInstance().getInt(
                                        Const.UID)}/${name}")
                            }
                            RequestType.ADD->{
                                ToastUtils.showLong("添加完成")
                                finish()
                            }

                            else -> {}
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {

        binding.newsaddTitle.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val length = s?.length
                binding.newsaddNum.setText("${length}/50")
                if(length==50){
                    binding.newsaddNum.setTextColor(getColor(com.frxuexi.lib_base.R.color.redfont))
                }else{
                    binding.newsaddNum.setTextColor(getColor(com.frxuexi.lib_base.R.color.darkgray))
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        binding.newsaddDate.setText(DateTimeUtils.getDate(System.currentTimeMillis()))

        binding.newaddIvdate.setOnClickListener {
            showDateDialog {
                binding.newsaddDate.setText(it)
            }
        }

        binding.newsaddIv.setOnClickListener {
            PictureSelector.create(this,PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }

        binding.newsAddRv.apply {
            adapter=newsImgAdapter
            layoutManager=GridLayoutManager(this@NesAddActivity,4)
        }



        binding.headAdd.setOnClickListener {
            val content = binding.newsaddContent.text.toString()
            val user = binding.newsaddUser.text.toString()
            val date = binding.newsaddDate.text.toString()
            val title = binding.newsaddTitle.text.toString()
            val type = binding.newsaddType.text.toString()
            val item =
                NewsBeanItem(true, content, null, imgs, date, true, user, title, type,0)
            vm.sendIntent(NewsIntent.addNews(item))
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==PictureSelector.SELECT_REQUEST_CODE && resultCode== RESULT_OK){
            val bean = data?.extras?.getParcelable<PictureBean>(PictureSelector.PICTURE_RESULT)
            val path = bean?.path!!
            newsImgAdapter.data.add(path)
            newsImgAdapter.notifyDataSetChanged()

            val split = path.split("/")
            val name = split.get(split.lastIndex)

            vm.sendIntent(NewsIntent.upload(name,path))
        }
    }

}